var DATE_SPLIT = "-"; 
var TIME_SPLIT = ":"; 
var PHONE_SPLIT = "-"; 

function showQuickOperate() {
    $("#formButtons-btn").show(); 
    $("#formButtons-btn_show").show(); 
    $("#formTips").css("bottom", "90px");
}

// 隐藏操作
function hideQuickOperate() {
    $("#formButtons-btn").hide(); // 正文： 操作按钮背景
    $("#formButtons-btn_show").hide(); // 正文： 操作按钮
    $("#formTips").css("bottom", "50px");  // 调整提示语句位置
}

function showFields() {
    if (!checkWordUrl()) {
        return
    }
    $("#survey").removeClass("editing");
    $("[id^=question_]").removeClass("editing").removeClass("focused").addClass("dragable");
    $("[id^=question_] > .fieldActions").css("visibility", "hidden");
    $("#stage").removeClass("afi cfo tms cfi").addClass("afi");
    $("#formProperties").hide();
    $("#fieldProperties").hide();
    $("#themeSide").hide();
    $("#themeDiv").hide();
    $("#main").show();
    $("#addFields").show();
    hideQuickOperate();
    showFieldsPosition()
}
function shakeFields() {
    if (!checkWordUrl()) {
        return
    }
    var a = 75;
    $("#addFields").animate({
        left: "+=15px"
    },
    a);
    $("#addFields").animate({
        left: "-=20px"
    },
    a);
    $("#addFields").animate({
        left: "+=20px"
    },
    a);
    $("#addFields").animate({
        left: "-=15px"
    },
    a);
    showFields()
}

function showFieldsPosition() {
    var a = 0;
    if ($("#userRsCountMsg").is(":visible")) {
        a = $("#userRsCountMsg").height()
    }
    if ((fieldtop + a) < $(document).scrollTop()) {
        $("#addFields").offset({
            top: $(document).scrollTop() - 15
        })
    } else {
        $("#addFields").offset({
            top: fieldtop + a
        })
    }
}

function showNoFieldPosition() {
    $("#qeditshownone").show();
    if ((fieldtop + 30) < $(document).scrollTop()) {
        $("#qeditshownone").offset({
            top: $(document).scrollTop() + 30
        })
    } else {
        $("#qeditshownone").offset({
            top: fieldtop + 30
        })
    }
}
function selectThemeCss() {
    $("#survey").removeClass("editing");
    $("#stage").removeClass("afi cfo tms cfi").addClass("tms");
    $("#addFields").hide();
    $("#formProperties").hide();
    showQuickOperate();
    $("#fieldProperties").hide()
}
function selectTheme() {
    selectThemeCss();
    $("#themeSide").show();
    $("#themeDiv").show();
    $("#main").hide()
}
function selectField() {
    if (!checkWordUrl()) {
        return
    }
    selectFieldCss();
    if ($("[id^=question_]").size() > 0) {
        var a = $("[id^=question_]").eq(0).attr("id").substring(9);
        showLeftQuestion(a)
    } else {
        $("#qeditshow").hide();
        $("#listButtons").hide();
        showNoFieldPosition()
    }
}
function selectFieldCss() {
    $("#survey").removeClass("editing");
    $("#stage").removeClass("afi cfo tms cfi").addClass("cfi");
    $("#addFields").hide();
    $("#formProperties").hide();
    $("#themeSide").hide();
    $("#themeDiv").hide();
    $("#main").show();
    showQuickOperate();
    $("#fieldProperties").show()
}
function selectForm() {
    $("#stage").removeClass("afi cfo tms cfi").addClass("cfo");
    $("[id^=question_]").removeClass("editing").removeClass("focused").addClass("dragable");
    $("[id^=question_] > .fieldActions").css("visibility", "hidden");
    $("#addFields").hide();
    $("#fieldProperties").hide();
    $("#themeSide").hide();
    $("#themeDiv").hide();
    $("#main").show();
    showQuickOperate();
    $("#formProperties").show();
    $("#survey").addClass("editing");
    showDescriptionEditor()
}

// 创建新问题
function newQuestion(a) {
    var b = createQuestionByID(a); //根据类型ID创建指定问题
    questionMap[b.id] = b; // 将问题添加入Map中
    return b
}

// 新增问题
function addQuestion(b, a) {
    /*if (!checkQuestionCount(b)) {
        return
    }*/
    editFlag = true; // 设置开始编辑状态
    var d = newQuestion(b); // 根据类型ID创建问题
    var c = getRightShowHtml(d); // 创建问题模板
    if ($("#sortable").find("li").length == 0) {
        $("#sortable").html(c)
    } else {
        if (a != undefined && a) {
            if ($("[id^=question_].editing").length > 0) {
                $("[id^=question_].editing").after(c)
            } else {
                $("#sortable").append(c)
            }
        } else {
            $("#sortable").append(c)
        }
    }
    refreshNO();
    refreshQuestionHeight(d.id);
    scrollQuestion(d.id);
    if (a != undefined && a) {
        showLeftQuestion(d.id)
    }
    if (b == "age") {
        checkFirstAge(d.id)
    }
    chkQestionCnt15(d.id)
}
function showEditSurvey() {
    selectForm()
}

// 显示调查问卷信息
function showSurveyInfo(b, a) {
    ajaxPost(ctx + "/model/getSurveyInfo.do", { // 从后台获取问卷信息
        surveyuuid: b,
        self: 0
    },
    function(c) { 
        if (c == null) {} else {
            if (c.error == "0") {
                showSurveyEditShow(b, c.msg, a); // 展示问卷信息
            } else {}
        }
    })
}

// 问卷显示处理
function showSurveyEditShow(c, h, e) {
	var k = "";
	var f = {};
	editQuestionMap = {};
	oldQuestionMap = {};
	initSurveyInfo(h.survey);
	if (h != null && h.pagelist != null) {
		for ( var j = 0; j < h.pagelist.length; j++) {
			var d = h.pagelist[j];
			f[d.id] = new Page(d);
			questionMap[d.id] = f[d.id];
			oldQuestionMap[d.id] = 1;
			if (j == 0) {
				firstpage = f[d.id]
			}
		}
	}
	if (h != null && h.questionlist != null) {
		var g = "";
		var a = "";
		for ( var j = 0; j < h.questionlist.length; j++) {
			var b = h.questionlist[j];
			if (g != b.pageid) {
				if (g != "") {
					k += getRightShowHtml(f[b.pageid])
				}
				g = b.pageid
			}
			oldQuestionMap[b.id] = 1;
			b.isedit = 1;
			questionMap[b.id] = new Question(b);
			k += getRightShowHtml(questionMap[b.id])
		}
	}
	if ($("#fieldProperties").is(":visible")) {
		hideQuickOperate()
	}
	if (h.questionlist.length > 0) {
		$("#sortable").html(k)
	} else {
		$("#sortable").html(getDefaultHtml())
	}
	refreshNO();
	refreshHeight();
	if (typeof (e) == "function") {
		e.call(this)
	}
	loadding = false
}
function getDefaultHtml() {
    return '<div class="notice" onclick=""><h2>←问卷未添加问题</h2><p>拖动或点击左侧题型后添加新问题，点击问题进行编辑</p></div>'
}
function refreshNO() {
    $("[id^=q_no_]").each(function(a) {
        $(this).html(questionPrefix + (a + 1) + ".")
    })
}
function refreshHeight() {
    $("[id^=coverlayer_]").each(function(a) {
        var b = $(this).attr("id").split("_")[1];
        refreshQuestionHeight(b)
    })
}
function refreshQuestionHeight(a) {
    $("#coverlayer_" + a).attr("height", $("#question_" + a).height() + 15)
}
function showSurveyTheme() {
    ajaxPost(ctx + "/json/surveytheme/ThemeList", {},
    function(a) {
        if (a == null) {} else {
            if (a.error == "0") {
                showSurveyThemeList(a.msg)
            } else {}
        }
    })
}
function showSurveyThemeList(d) {
    var b = "";
    var c = "";
    for (var a = 0; a < d.length; a++) {
        if (d[a].id == survey.themeid) {
            c = " selected"
        } else {
            c = ""
        }
        b += '<option value="' + d[a].id + '" ' + c + ">" + d[a].title + "</option>"
    }
    b += "";
    $("#formTheme").html(b);
    setTimeout(setSurveyProperties, 500)
}
function setSurveyProperties() {
    if ((typeof survey.themeid == "undefined") || (typeof survey.type == "undefined")) {
        setTimeout(setSurveyProperties, 500)
    } else {
        $("#formTheme").val(survey.themeid);
        $("#surveyCatalogSelect").val(survey.type)
    }
}
function initTemplateQuestion() {
    ajaxPost(ctx + "/json/question/TemplateQuestion", {},
    function(a) {
        if (a == null) {} else {
            if (a.error == "0") {
                initTemplateQuestionList(a.msg)
            } else {}
        }
    })
}
var TemplateQuestionListHtml = "";
function initTemplateQuestionList(f) {
    var g = 20 * 2;
    var c = "";
    var e = "";
    for (var b = 0; b < f.length; b++) {
        var d = f[b];
        TemplateQuestionMap[d.id] = d;
        var a = d.description;
        if (getStringLength(a) > g) {
            a = getStringByByte(a, g - 2) + ".."
        }
        c += '<li><a href="javascript:void(0);" onclick="initTemplatequestionAnswerList(\'' + d.id + "');return false;\">" + a + "</a></li>"
    }
    TemplateQuestionListHtml = c
}
function getTemplateQuestionListHtml() {
    return TemplateQuestionListHtml
}
function initTemplatequestionAnswerList(f) {
    var e = TemplateQuestionMap[f];
    var d = "";
    if (e.answers != null) {
        for (var c = 0; c < e.answers.length; c++) {
            var b = e.answers[c];
            if (c != 0) {
                d += "\r\n"
            }
            d += b.name
        }
    }
    $("#templatequestionanswerlist").val(d)
}
function copyQ() {
    if (targetid != "") {
        copyQuestion(targetid)
    }
}
function deleteQ() {
    if (targetid != "") {
        deleteQuestion(targetid)
    }
}
function saveSurvey(b, n, c) {
    if (loadding) {
        return
    }
    if (!checkWordUrl()) {
        return
    }
    if (survey.name == "") {
        if (n == "2") {
            closeArtDialog("checkeditlogicDIV")
        }
        if (n == "3") {
            closeArtDialog("checkviewsurveyDIV")
        }
        if (n == "4") {
            closeArtDialog("checkEditThemeDIV")
        }
        selectForm();
        $("#formName").focus();
        showSaveErrorMsg(formatMessage("edit_001"));
        return
    }
    var e = new Array();
    $("[id^=question_]").each(function(i) {
        var p = questionMap[$(this).attr("id").substring(9)];
        if (p.showtype == "page") {
            e.push({
                id: p.id,
                index: i,
                buttontype: p.buttontype
            })
        }
    });
    var o = false;
    var j = "";
    if ($("[id^=question_]").length == 1) {
        var m = questionMap[$("[id^=question_]").attr("id").substring(9)];
        if (m.showtype == "page") {
            o = true;
            j = formatMessage("edit_015")
        }
    } else {
        if (e.length > 0) {
            if (e[0].index == 0) {
                o = true;
                j = formatMessage("edit_002", 1)
            } else {
                for (var g = 0; g < e.length - 1; g++) {
                    if ((e[g + 1].index - e[g].index) == 1) {
                        o = true;
                        j = formatMessage("edit_002", g + 2);
                        break
                    }
                }
            }
        }
    }
    if (o) {
        if (n == "2") {
            closeArtDialog("checkeditlogicDIV")
        }
        if (n == "3") {
            closeArtDialog("checkviewsurveyDIV")
        }
        if (n == "4") {
            closeArtDialog("checkEditThemeDIV")
        }
        showSaveErrorMsg(j);
        return
    } else {
        if (firstpage.id == "") {
            firstpage.id = (new Date()).getTime() + "";
            firstpage.buttontype = 0
        }
        if (e.length > 0) {
            e.splice(0, 0, {
                id: firstpage.id,
                index: 0
            })
        } else {
            e.push({
                id: firstpage.id,
                index: 0
            })
        }
    }
    var l = 0;
    var h = e[0].id;
    var k = false;
    var f = "";
    var d = new Array();
    var a = false;
    $("[id^=question_]").each(function(q) {
        var t = questionMap[$(this).attr("id").substring(9)];
        if (t.showtype == "page") {
            l++;
            if (l < e.length) {
                h = e[l].id
            }
        } else {
            if (t.type != 0) {
                a = true
            }
            t.pageid = h;
            d.push(t);
            if (t.description == "" && t.imageurl == "") {
                k = true;
                showLeftQuestion(t.id);
                $("#qleftdescription").focus();
                showSaveErrorMsg(formatMessage("edit_004"));
                f = formatMessage("edit_004");
                return
            }
            if (t.typeid == 1 && (t.type == 1 || t.type == 2 || t.type == 41 || t.type == 42)) {
                for (var r = 0; r < t.answers.length; r++) {
                    var p = t.answers[r];
                    if (p.name == "" && p.imageurl == "") {
                        k = true;
                        showLeftQuestion(t.id);
                        $("#qleftanswername_" + t.id + "_" + p.id).focus();
                        showSaveErrorMsg(formatMessage("edit_005"));
                        f = formatMessage("edit_005");
                        return
                    }
                }
                if (t.type == 41 || t.type == 42) {
                    for (var r = 0; r < t.questions.length; r++) {
                        var s = t.questions[r];
                        if (s.description == "") {
                            k = true;
                            showLeftQuestion(t.id);
                            $("#qleftquestiondescription_" + t.id + "_" + s.id).focus();
                            showSaveErrorMsg(formatMessage("edit_006"));
                            f = formatMessage("edit_006");
                            return
                        }
                    }
                }
            }
        }
    });
    if (k) {
        if (n == "2") {
            closeArtDialog("checkeditlogicDIV")
        }
        if (n == "3") {
            closeArtDialog("checkviewsurveyDIV")
        }
        if (n == "4") {
            closeArtDialog("checkEditThemeDIV")
        }
        return
    }
    if (!a) {
        if ($("[id^=question_]").length > 0) {
            if (n == "2") {
                closeArtDialog("checkeditlogicDIV")
            }
            if (n == "3") {
                closeArtDialog("checkviewsurveyDIV")
            }
            if (n == "4") {
                closeArtDialog("checkEditThemeDIV")
            }
            showSaveErrorMsg(formatMessage("edit_015"));
            return
        }
    }
    if (!editFlag) {
        $("#saveText").html("保存问卷中......");
        $("#saveText").html("保存问卷");
        $("#showSaveSuccess").html(formatMessage("edit_007"));
        $("#showSaveSuccess").show();
        setTimeout(function() {
            $("#showSaveSuccess").hide()
        },
        3000);
        return
    }
    saveSurveyAction(b, e, d, n, c)
}
function showSaveErrorMsg(a) {
    showErrorMsg("showSaveError", "showSaveError", a)
}
function showErrorMsg(c, a, b) {
    $("#" + a).html(b);
    $("#" + c).show();
    setTimeout(function() {
        $("#" + c).hide()
    },
    3000)
}
function saveSurveyAction(b, e, f, a, d) {
    disableButton(b, -1);
    var g = "";
    if (a == "1") {
        g = "#saveText"
    } else {
        g = "#saveFormDiv"
    }
    $(g).html("保存问卷中......");
    var c = -1;
    if ($("#fieldProperties").is(":visible")) {
        $("[id^=question_]").each(function(h) {
            if ($(this).hasClass("editing")) {
                c = h
            }
        })
    }
    alert($.toJSON(survey));
    alert($.toJSON(e));
    alert($.toJSON(f));
    ajaxPost(ctx + "/model/updateSurvey.do", {
    	surveyuuid: SURVEYID,
        survey: $.toJSON(survey),
        pagelist: $.toJSON(e),
        questionlist: $.toJSON(f)
    },
    function(h) {
        enableButton(b);
        $(g).html("保存问卷");
        if (h == null) {
            showSaveErrorMsg(formatMessage("common_001"))
        } else {
            if (h.error == "0") {
                editFlag = false;
                if (typeof(d) == "function") {
                    d.call(this)
                }
                if (a == "3") {
                    closeArtDialog("checkviewsurveyDIV")
                }
                if (a == "4") {
                    closeArtDialog("checkEditThemeDIV");
                    loadThemePanelLayer()
                }
                showSurveyInfo(survey.id, 
                function() {
                    if ($("#fieldProperties").is(":visible")) {
                        if (c != -1) {
                            var i = $("[id^=question_]").eq(c).attr("id");
                            showLeftQuestion(i.split("_")[1])
                        }
                    }
                    if (a == "1") {
                        $("#showSaveSuccess").html(formatMessage("edit_007"));
                        $("#showSaveSuccess").show();
                        setTimeout(function() {
                            $("#showSaveSuccess").hide()
                        },
                        3000)
                    }
                })
            } else {
                if (h.field == "-1" && h.msg == "-1") {
                    editFlag = false;
                    showNoSurvey()
                } else {
                    showSaveErrorMsg(formatMessage("common_001"))
                }
            }
        }
    })
}

// -- 检查问题数量
function checkQuestionCount(a) {
    var b = 0;
    if (a == "pagebreak" || a == "blank") {
        return true
    }
    $("[id^=question_]").each(function(d) {
        var e = questionMap[$(this).attr("id").substring(9)];
        if (e.showtype != "page" && e.type > 0) {
            b++
        }
    });
 
    if (auth.f_rs_question_count != -1 && b >= auth.f_rs_question_count) {
        var c = QuestionCountInfo();
        $("#poptips").html(c);
        showPopTips();
        return false
    } else {
        return true
    }
}
function QuestionCountInfo() {
    var a = "";
    a += closePopTipsHtml();
    a += formatMessage("poptips001", roleName, auth.f_rs_question_count, (roleCode != "ts-public" ? '<a class="btn-b" href="' + ctx + '/services">查看定制服务</a>': '<a class="btn-b" href="' + ctx + '/version/upgrade">立即升级</a>'));
    return a
}
function SamplecountInfo() {
    var a = "";
    a += closePopTipsHtml();
    a += formatMessage("poptips002", roleName, auth.f_rs_sample_count > 0 ? auth.f_rs_sample_count: "无限", (roleCode != "ts-public" ? (auth.f_rs_sample_count > 0 ? '<a class="btn-b" href="' + ctx + '/version/upgrade">立即升级</a>': '<a class="btn-b" href="' + ctx + '/services">查看定制服务</a>') : '<a class="btn-b" href="' + ctx + '/version/upgrade">立即升级</a>'));
    return a
}
function recordQuestionEdit(a) {
    editFlag = true;
    editQuestionMap[a] = 1
}
function chkHasQuestion() {
    var f = $("[id^=question_]");
    var b = f.length;
    var c = 0;
    if (b > 0) {
        for (var a = 0; a < b; a++) {
            var e = $(f[a]);
            var g = e.attr("id").substring(9);
            var d = questionMap[g];
            if (d.showtype == "page") {
                c++
            }
        }
        if (c < b) {
            return true
        }
    }
    return false
}
function chkQestionCnt15(a) {
    if (getQuestionCount() > 15) {
        checkFirstOut(a)
    }
}
function getQuestionCount() {
    var f = $("[id^=question_]");
    var b = f.length;
    var c = 0;
    if (b > 0) {
        for (var a = 0; a < b; a++) {
            var e = $(f[a]);
            var g = e.attr("id").substring(9);
            var d = questionMap[g];
            if (d.showtype == "page") {
                c++
            }
            if (d.type == 0) {
                c++
            }
        }
    }
    return b - c
};